<?php

declare(strict_types=1);

namespace app\operations\controller\admin;

use think\Request;
use think\Response;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use think\facade\Db;
use app\seller\model\Apply as ApplyModel;
use app\user\model\User as UserModel;
use app\admin\model\auth\Admin as AdminModel;
use app\seller\model\Organ as OrganModel;

use app\seller\model\Store as StoreModel;
use app\operations\model\CutepetApply as CutepetApplyModel;

use sheep\controller\traits\Crud;


//门店申请
class Apply extends Backend
{
    use Crud;
    protected $model = null;
    protected $userModel = null;
    protected $organModel = null;
    protected $adminModel = null;
    protected $storeModel = null;

    protected function initialize()
    {
        $this->model = new ApplyModel;
        $this->userModel = new UserModel;
        $this->organModel = new OrganModel;
        $this->adminModel = new AdminModel;
        $this->storeModel = new StoreModel;
    }


    /**
     * 查看
     *
     * @return Response
     */
    public function list(Request $request): Response
    {

        $list = $this->model->with(['user'])->sheepFilter()->paginate($request->param('list_rows', 10));

        foreach($list as &$val){
            $val['inviter_name'] = '';
        }

        return success('获取成功', $list);
    }


    public function audit($id)
    {
        // 转换ID为整数类型
        $id = intval($id);

        // 获取请求的 'status' 和 'remark' 参数
        $params = $this->request->only(['status', 'remark']);

        // 查找审核申请记录，使用 find() 获取单条记录
        $apply = $this->model->where('id', $id)->find();

        // 如果申请记录不存在，返回错误信息
        if (!$apply) {
            return error('未找到该数据');
        }

        // 如果申请已经通过审核，返回错误信息
        if ($apply->status == 1) {
            return error('已通过审核');
        }

        // 如果 status 值是 1 或 2，执行审核逻辑
        if (in_array($params['status'], [1, 2])) {
            // 使用事务处理，确保数据一致性
            $flag = Db::transaction(function () use ($apply, $params) {
                // 更新申请状态和备注，确保有正确的条件
                $apply->status = $params['status'] ?? '0';
                $apply->remark = $params['remark'] ?? '';
                $apply->save();  // save() 自带主键更新，不需要再显式条件

                // 更新 CutepetApplyModel 中的状态和备注，确保传入正确的条件
                CutepetApplyModel::where('id', $apply->id)
                    ->update([
                        'status' => $apply->status,
                        'remark' => $apply->remark
                    ]);

                // 如果审核通过，执行以下逻辑
                if ($params['status'] == 1) {
                    // 检查是否已有管理员账号，使用 find() 代替 first()
                    $admin = $this->adminModel->where('mobile', $apply->mobile)->find();

                    // 如果没有，创建新商家账号和组织
                    if (!$admin) {
                        $admin = $this->createAdminAccount($apply);
                    }

                    // 分割申请的服务类别
                    $serveList = explode(',', $apply->serve);

                    // 遍历每个服务类别，创建对应类型的店铺
                    foreach ($serveList as $serve) {
                        $this->createShopStore($admin->organ_id, $serve, $apply->mobile,$apply->level);
                    }
                }
            });

            // 根据事务执行结果返回响应
            return $flag === false ? error('审核失败') : success('审核成功');

        } else {
            return error('未知错误', $id);
        }
    }

    /**
     * 创建商家账号及组织
     *
     * @param object $apply 申请对象
     * @return object 返回创建的管理员对象
     */
    private function createAdminAccount($apply)
    {
        // 创建组织信息
        $organ = $this->organModel->create([
            'name' => time() . mt_rand(100000, 999999)
        ]);

        // 创建商家账号
        $salt = mt_rand(1000, 9999);
        $adminData = [
            'role_id' => 3,
            'account' => $apply->mobile,
            'nickname' => $apply->name,
            'mobile' => $apply->mobile,
            'password' => md5(md5('123456') . $salt),
            'salt' => $salt,
            'avatar' => '/storage/default/20240726/8571d585e635c4ea380b6db352f8d38c.png',
            'status' => 'normal',
            'create_time' => time(),
            'update_time' => time(),
            'legal_person_name' => $apply->legal_person_name,
            'legal_id_type' => $apply->legal_id_type,
            'legal_id_images' => $apply->protrait_card . ',' . $apply->reverse_card,
            'entity_type' => $apply->entity_type,
            'entity_name' => $apply->entity_name,
            'business_license' => $apply->business_license,
            'organ_id' => $organ->id,
        ];

        return $this->adminModel->create($adminData);
    }

    /**
     * 创建店铺
     *
     * @param int $organId 组织ID
     * @param int $serve 服务类别
     * @param string $mobile 联系电话
     * @throws SheepException
     */
    private function createShopStore($organId, $serve, $mobile,$level)
    {
        // 根据服务类型决定店铺类型
        $type = $serve == 1 ? 2 : 1;

        // 检查该类型店铺是否已存在
        $existingStoreCount = Db::name('shop_store')
            ->where('organ_id', $organId)
            ->where('type', $type)
            ->count();

        // 如果该商家已存在该类型店铺，抛出异常，事务回滚
        if ($existingStoreCount > 0) {
            throw new SheepException('该商家已经有该类型门店');
        }

        // 创建新店铺记录
        Db::name('shop_store')->insert([
            'name' => '', // 店铺名称
            'type' => $type, // 店铺类型
            'mobile' => $mobile, // 联系电话
            'level' => 'bronze', // 店铺等级
            'mark' => 5, // 店铺评分
            'other_mark' => 5, // 其他评分
            'organ_id' => $organId, // 组织ID
            'security_deposit' => '5000.00', // 保障金金额
            'vip' => $level, // 会员等级
            'create_time' => time(),
            'update_time' => time(),
        ]);
    }



    /**
     * 门店详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $data = $this->model->with('user')->findOrFail($id);

        $data['inviter_name'] = '';

        return success('获取成功', $data);
    }



}
